package com.qf.service.impl;

import com.qf.dao.CommentMapper;
import com.qf.dao.LoveshowMapper;
import com.qf.dao.ShowImgDao;
import com.qf.dao.UserMapper;
import com.qf.dto.ShowDto;
import com.qf.entity.Loveshow;
import com.qf.entity.Showimg;
import com.qf.entity.User;
import com.qf.service.LoveShowService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author chen
 * @version 1.0
 * @date 2019/10/24 13:03
 */
@Service
public class LoveShowserviceImpl implements LoveShowService {
    @Resource
    private LoveshowMapper loveshowMapper;
    @Resource
    private ShowImgDao showImgDao;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CommentMapper commentMapper;

    @Override
    @Transactional
    public void addShow(String showText, MultipartFile multipartFile, int userid, HttpServletRequest request) {
        Loveshow loveshow = new Loveshow();
        loveshow.setShowtext(showText);
        loveshow.setUserid(userid);
        loveshowMapper.addShow(loveshow);

        Integer showid = loveshow.getShowid();

            String realPath = request.getServletContext().getRealPath("/img/showimg");
            String originalFilename = multipartFile.getOriginalFilename();
            String filename = System.currentTimeMillis()+originalFilename.substring(originalFilename.lastIndexOf("."));
            File file1 = new File(realPath + "/" + filename);
            try {
                multipartFile.transferTo(file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Showimg showimg = new Showimg();
            showimg.setShowid(showid);
            showimg.setShowimgname(originalFilename);
            showimg.setShowimgurl("/img/showimg"+"/" + filename);
            showImgDao.insert(showimg);

    }

    @Override
    public ShowDto getShowByShowId(Integer showId) {
        Loveshow loveshow = loveshowMapper.getShowByShowId(showId);
        ShowDto showDto = new ShowDto();
        BeanUtils.copyProperties(loveshow, showDto);
        User u = userMapper.getLoveUser(showDto.getUserid());
        showDto.set_user(u.getKickname());
        showDto.set_userid(u.getUserid());

        int commentCount = commentMapper.getCommentCount(showDto.getShowid());
        showDto.setCommentCount(commentCount);
        return showDto;
    }


}
